﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BackGroundParallax : MonoBehaviour
{

    public Transform[] backgrounds;//所有的背景层，这里，离玩家最近的背景的下标i最小，当i足够大时，背景和相机是一起位移的，比如真实世界里，人走动的时候，周围的房屋都向后移动，而天空中的星星却看起来没有移动过
    public float parallaxScale;//相对相机的移动补偿的比例值
    public float parallaxScaleReductionFactor;//对于不同的背景层的移动补偿的差值比例
    public float smoothing;

    private Transform cam;
    private Vector3 previousCamPos;//相机在上一帧的位置

    // Use this for initialization
    void Start()
    {
        cam = Camera.main.transform;
        previousCamPos = cam.position;
    }

    // Update is called once per frame
    void Update()
    {
        float parallax = (previousCamPos.x - cam.position.x) * parallaxScale;//根据相机的单帧位移获得补偿值大小

        for (int i = 0; i < backgrounds.Length; i++)
        {
            //获得位移的x值，i*parallaxScaleReductionFactor得到不同背景层的补偿差
            float backgroundTargetPosX = backgrounds[i].position.x + parallax * (i * parallaxScaleReductionFactor + 1);

            Vector3 backgroundTargetPos = new Vector3(backgroundTargetPosX, backgrounds[i].position.y, backgrounds[i].position.z);
            backgrounds[i].position = Vector3.Lerp(backgrounds[i].position, backgroundTargetPos, smoothing * Time.deltaTime);
        }
        previousCamPos = cam.position;
    }
}